<template>
  <view class="container">


    <!-- 商品主图 -->
    <scroll-view class="content" scroll-y>
      <view class="product-image">
        <image class="main-image" :src="goodsDetail.image" mode="aspectFill" />
      </view>

      <!-- 商品标题 -->
      <view class="product-title">
        <text class="title-text">{{ goodsDetail.name }}</text>
      </view>

      <!-- 价格区域 -->
      <view class="price-section">
        <view class="price-info">
          <text class="currency">¥</text>
          <text class="current-price">{{ goodsDetail.price }}</text>
          <text class="original-price">¥{{ goodsDetail.mktprice }}</text>
        </view>
      </view>

      <!-- 规格选择 -->
      <view v-if="goodsDetail.spes.length > 0" class="spec-section" @click="openSpecPopup">
        <text class="spec-label">选择</text>
        <view class="spec-value">
          <text>{{ selectedSpec.name || '规格' }}</text>
          <uni-icons type="right" size="14" color="#999" />
        </view>
      </view>

      <!-- 店铺信息 -->
      <view class="shop-info">
        <view class="shop-header">
          <image class="shop-logo" :src="shoplogo" mode="aspectFill" />
          <text class="shop-name">宝道商贸</text>
        </view>
        <view class="shop-scores">
          <view class="score-item">
            <text class="score-label">描述相符</text>
            <text class="score-value">4.8</text>
          </view>
          <view class="score-item">
            <text class="score-label">物流服务</text>
            <text class="score-value">4.8</text>
          </view>
          <view class="score-item">
            <text class="score-label">服务态度</text>
            <text class="score-value">4.8</text>
          </view>
        </view>
      </view>
      <view class="product-description">
        <view class="description-title">商品描述</view>
        <view class="description-content">
          <rich-text :nodes="goodsDetail.intro"></rich-text>
        </view>
      </view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="bottom-bar pb-100">
      <view class="action-buttons">
        <view class="service-btn" @click="contactService">
          <uni-icons type="headphones" size="24" />
          <text>客服</text>
        </view>
      </view>
      <view class="buy-buttons">
        <button class="buy-now-btn" @click="buyNow">立即购买</button>
      </view>


    </view>

    <!-- 规格选择弹窗 -->
    <uni-popup ref="specPopup" type="bottom">
      <view class="spec-popup">
        <view class="spec-popup-header">
          <text class="spec-popup-title">选择规格</text>
          <uni-icons type="closeempty" size="20" @click="closeSpecPopup" />
        </view>
        <view class="spec-options">
          <view v-for="(item, index) in goodsDetail.spes" :key="index"
            :class="['spec-option', selectedSpec === item ? 'selected' : '']" @click="selectSpec(item)">
            <text>{{ item.name }}</text>
          </view>
        </view>
        <button class="confirm-btn" @click="confirmSpec">确定</button>
      </view>
    </uni-popup>
  </view>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { getGoodsDetailAPI } from '@/service/index/index'
import { useRoute } from 'vue-router'
import { useUserStore } from '@/store/user'
import shoplogo from '@/static/images/circle.jpg'
import safeArea from '@/components/safeArea.vue'

// 定义商品详情类型
interface GoodsDetail {
  id?: number
  name?: string
  price?: number
  mktprice?: number
  image?: string
  intro?: string
  spes?: Array<{ name: string }>
  admin_tel?: string[]
}
const route = useRoute()
const userStore = useUserStore()
const specPopup = ref()
const selectedSpec = ref('')
const specs = ['2ml*30支', '5ml*30支', '10ml*30支']
const goodsDetail = ref<GoodsDetail>({})
const serverUrl = import.meta.env.VITE_SERVER_BASEURL
const goBack = () => {
  uni.navigateBack()
}

const openSpecPopup = () => {
  specPopup.value.open()
}

const closeSpecPopup = () => {
  specPopup.value.close()
}

const selectSpec = (spec: string) => {
  selectedSpec.value = spec
}

const confirmSpec = () => {
  if (!selectedSpec.value) {
    uni.showToast({
      title: '请选择规格',
      icon: 'none',
    })
    return
  }
  closeSpecPopup()
}

const contactService = () => {


  let arr = goodsDetail.value.admin_tel
  uni.showActionSheet({
    itemList: arr,
    success: (res) => {
      if (res.tapIndex === 0) {
        //#ifdef APP-PLUS || MP-WEIXIN
        uni.makePhoneCall({
          phoneNumber: arr[res.tapIndex],
        })
        //#endif
      }
    }
  })

}

const buyNow = () => {
  if (goodsDetail.value.spes.length > 0 && !selectedSpec.value) {
    openSpecPopup()
    return
  }
  if (!userStore.userInfo.token) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
    })
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/login/login',
      })
    }, 1000)
    return
  }
  if (goodsDetail.value.spes.length > 0) {
    uni.navigateTo({
      url: '/pages/goods/order_confirm?id=' + id.value + '&spec=' + selectedSpec.value.name,
    })
  } else {
    uni.navigateTo({
      url: '/pages/goods/order_confirm?id=' + id.value,
    })
  }

}
// 解析HTML内容，提取图片地址并追加serverUrl
const parseHtmlContent = (htmlContent: string) => {
  if (!htmlContent) return htmlContent

  // 使用正则表达式匹配img标签的src属性
  const imgRegex = /<img([^>]*?)src=["']([^"']*?)["']([^>]*?)>/gi

  return htmlContent.replace(imgRegex, (match, beforeSrc, srcValue, afterSrc) => {
    // 如果src已经是完整URL，直接返回
    if (srcValue.startsWith('http://') || srcValue.startsWith('https://')) {
      return match
    }

    // 如果src以/开头，追加serverUrl
    if (srcValue.startsWith('/')) {
      const newSrc = serverUrl + srcValue
      return `<img${beforeSrc}src="${newSrc}"${afterSrc}>`
    }

    // 其他情况，在src前添加serverUrl
    const newSrc = serverUrl + '/' + srcValue
    return `<img${beforeSrc}src="${newSrc}"${afterSrc}>`
  })
}

const getGoodsDetail = async () => {
  const res = await getGoodsDetailAPI({ id: id.value })
  console.log(res)
  if (res.code === 1) {
    goodsDetail.value = res.data?.info
    // 解析商品介绍内容中的图片地址
    if (goodsDetail.value.intro) {
      goodsDetail.value.intro = parseHtmlContent(goodsDetail.value.intro)
    }
  }
}
const id = ref(0)
//#ifdef APP-PLUS || MP-WEIXIN
onLoad((options) => {
  id.value = Number(options.id)
  getGoodsDetail()
})
//#endif
//#ifdef  H5
onMounted(() => {
  id.value = Number(route.query.id)
  getGoodsDetail()
})
//#endif


</script>

<style>
page {
  height: 100%;
}

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f8f8f8;
}

.nav {
  position: relative;
  display: flex;
  align-items: center;
  height: 88rpx;
  padding: 0 30rpx;
  background-color: #fff;
}

.back-icon {
  width: 40rpx;
  height: 40rpx;
}

.nav-title {
  flex: 1;
  margin-right: 40rpx;
  font-size: 16px;
  color: #333;
  text-align: center;
}

.content {
  flex: 1;
  overflow: auto;
  padding-bottom: 200rpx;
}

.product-image {
  width: 750rpx;
  height: 400rpx;
  background-color: #fff;
}

.main-image {
  width: 100%;
  height: 400rpx;
}

.product-title {
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.title-text {
  font-size: 14px;
  line-height: 1.4;
  color: #666;
}

.price-section {
  padding: 20rpx 30rpx;
  margin-top: 20rpx;
  background-color: #fff;
}

.price-info {
  display: flex;
  align-items: baseline;
}

.currency {
  font-size: 16px;
  color: #ff4444;
}

.current-price {
  margin-right: 20rpx;
  font-size: 24px;
  font-weight: bold;
  color: #ff4444;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.spec-section {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  margin-top: 20rpx;
  background-color: #fff;
}

.spec-label {
  font-size: 14px;
  color: #333;
}

.spec-value {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #999;
}

.shop-info {
  padding: 30rpx;
  margin-top: 20rpx;
  background-color: #fff;
}

.shop-header {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;
}

.shop-logo {
  width: 80rpx;
  height: 80rpx;
  margin-right: 20rpx;
  border-radius: 50%;
}

.shop-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.shop-scores {
  display: flex;
  justify-content: space-around;
}

.score-item {
  text-align: center;
}

.score-label {
  margin-bottom: 10rpx;
  font-size: 12px;
  color: #999;
}

.score-value {
  font-size: 14px;
  color: #ff4444;
}

.bottom-bar {
  display: flex;
  align-items: center;
  height: 100rpx;
  padding: 0 30rpx;
  padding-bottom: 40rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
}

.action-buttons {
  display: flex;
  margin-right: 30rpx;
}

.service-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.service-btn text {
  margin-top: 4rpx;
  font-size: 12px;
  color: #666;
}

.buy-buttons {
  display: flex;
  flex: 1;
  gap: 20rpx;
}

.buy-now-btn {
  display: flex;
  flex: 1;
  align-items: center;
  justify-content: center;
  height: 72rpx;
  font-size: 14px;
  color: #fff;
  background-color: #1890ff;
  border-radius: 36rpx;
}

.spec-popup {
  padding: 30rpx;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

.spec-popup-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 30rpx;
}

.spec-popup-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.spec-options {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
  margin-bottom: 40rpx;
}

.spec-option {
  padding: 20rpx 40rpx;
  border: 1px solid #ddd;
  border-radius: 30rpx;
}

.spec-option.selected {
  background-color: #fef0f0;
  border-color: #ff4444;
}

.spec-option text {
  font-size: 14px;
  color: #333;
}

.confirm-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 80rpx;
  font-size: 16px;
  color: #fff;
  background-color: #1890ff;
  border-radius: 40rpx;
}

.product-description {
  padding: 30rpx;
  margin-top: 20rpx;
  background-color: #fff;
}

.description-title {
  font-size: 32rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.description-content {
  font-size: 28rpx;
  color: #666;
}
</style>
